<template>
  <el-drawer v-model="visible" :show-close="false" width="30%" append-to-body @close="handleClose">
    <template #header>
      <div class="flex-x-between">
        <span>规格管理</span>
        <el-button type="primary" link size="small" icon="plus" @click="handleAddSpec">
          新增
        </el-button>
      </div>
    </template>
    <BasePageTable
      :tableData="tableData"
      :loading="loading"
      :pageNum="queryPage.pageNum"
      :pageSize="queryPage.pageSize"
      :total="queryPage.total"
      :tableColumnsData="tableColumnsData"
      v-bind="tableProps"
      @handleQuery="handleQuery"
      @sort-change="handleSortChange"
    >
      <template #specType="scope">
        {{ specTypeOptionsObj[scope.row.specTagId]?.name }}
      </template>
      <template #handle="scope">
        <el-button type="primary" link size="small" icon="edit" @click.stop="handleEdit(scope.row)">
          编辑
        </el-button>
        <el-button
          type="danger"
          link
          size="small"
          icon="delete"
          @click.stop="handleDelete(scope.row)"
        >
          删除
        </el-button>
      </template>
    </BasePageTable>
  </el-drawer>
  <!-- 规格的弹框 -->
  <el-dialog v-model="specVisible" :title="specTitle" width="30%">
    <el-form :model="specFormData" :rules="specRules" label-width="100px" ref="specFormRef">
      <el-form-item label="所属属性" prop="specTagId">
        <el-select v-model="specFormData.specTagId" placeholder="请选择所属属性">
          <el-option
            v-for="item in specTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="specFormData.name" placeholder="请输入规格名称" />
      </el-form-item>
      <div class="flex-x-end">
        <el-form-item>
          <el-button type="primary" @click="submitAddSpec">确认</el-button>
        </el-form-item>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { useEquityMallStoreHook } from "@/store/modules/equitymall";
import EquityMallAPI from "@/api/equitymall";
const equityMallStore = useEquityMallStoreHook();
const tableProps = ref({
  defaultSort: { prop: "specType", order: "descending" },
});
const props = defineProps({
  specTypeOptions: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(["updateSpecTag"]);
const visible = ref(false);
const isFullscreen = ref(false); // 控制全屏状态
// 关闭弹窗
const handleClose = () => {
  visible.value = false;
};
const openDialog = async () => {
  visible.value = true;
};
const queryPage = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const tableData = ref([
  {
    id: 1,
    name: "颜色",
    hasChildren: true,
    children: [
      {
        subId: 1,
        name: "白色",
        specTagId: 1,
      },
      {
        subId: 2,
        name: "黑色",
        specTagId: 1,
      },
    ],
  },
  {
    id: 2,
    name: "尺码",
    hasChildren: true,
    children: [
      {
        subId: 1,
        name: "大",
        specTagId: 2,
      },
      {
        subId: 2,
        name: "小",
        specTagId: 2,
      },
    ],
  },
]);
const loading = ref(false);
const tableColumnsData = ref([
  {
    label: "规格名称",
    prop: "name",
  },
  {
    label: "所属属性",
    sortable: true,
    prop: "specType",
    customSlot: "specType",
  },
  {
    label: "操作",
    prop: "handle",
    customSlot: "handle",
    align: "right",
    showOverflowTooltip: true,
  },
]);
const handleSortChange = ({ column, prop, order }) => {
  // if (prop === "specType") {
  //   tableData.value.sort((a, b) => {
  //     if (a.specType < b.specType) return -1;
  //     if (a.specType > b.specType) return 1;
  //     return 0;
  //   });
  // } else {
  //   // 其他列的默认排序逻辑
  //   tableData.value.sort((a, b) => {
  //     if (a[prop] < b[prop]) return -1;
  //     if (a[prop] > b[prop]) return 1;
  //     return 0;
  //   });
  // }
};
const handleQuery = () => {
  console.log("handleQuery");
};

const specTagVisible = ref(false);
const specTypeOptionsObj = ref({});
const setSpecData = async () => {
  console.log(props.specTypeOptions, "props.specTypeOptions");
  // 拼接树形数据
  let specTypeIds = [];
  props.specTypeOptions.forEach((item) => {
    specTypeIds.push(item.id);
    specTypeOptionsObj.value[item.id] = item;
  });
  console.log(specTypeOptionsObj.value, "specTypeOptionsObj.value");
  let specData = await equityMallStore.handleSpecLoad(specTypeIds);
  equityMallStore.setAllSpecOptionsObj(specData);
  console.log(equityMallStore.getAllSpecOptionsObj(), "equityMallStore.getAllSpecOptionsObj()");
  console.log(specData, "specData");
  tableData.value = specData;
  console.log(tableData.value, "tableData.value");
};
const specVisible = ref(false);
const specTitle = ref("");
const activeSpec = ref({
  specTagId: "",
  name: "",
});
const specFormData = ref({
  specTagId: "",
  name: "",
});
const specRules = ref({
  specTagId: [{ required: true, message: "请选择所属属性", trigger: "blur" }],
  name: [{ required: true, message: "请输入规格名称", trigger: "blur" }],
});
// 删除
const deleteProductSpec = async (id) => {
  try {
    await EquityMallAPI.deleteProductSpec(id);
    setSpecData();
    specTagVisible.value = false;
    ElMessage.success("删除成功");
  } catch (error) {
    console.error(error);
  }
};
const handleAddSpec = (row) => {
  console.log(row, "新增规格");
  specFormData.value = {
    specTagId: "",
    name: "",
  };
  specVisible.value = true;
  specTitle.value = `新增规格`;
};
const handleEdit = (row) => {
  console.log(row, "编辑");
  specVisible.value = true;
  specTitle.value = `编辑规格`;
  specFormData.value.name = row.name;
  specFormData.value.specTagId = row.specTagId;
  specFormData.value.id = row.id;
};
const handleDelete = (row) => {
  console.log(row, "删除");
  ElMessageBox.confirm("确定要删除属性吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteProductSpec(row.id);
  });
};
const specFormRef = ref(null);
const submitAddSpec = () => {
  specFormRef.value.validate((valid) => {
    console.log(valid, "valid");
    if (valid) {
      if (!specFormData.value?.id) {
        addProductSpec();
      } else {
        // 编辑规格
        editProductSpec();
      }
    }
  });
};
const addProductSpec = async () => {
  try {
    console.log(specFormData.value, "specFormData.value");
    const res = await EquityMallAPI.addProductSpec({
      name: specFormData.value.name,
      specTagId: specFormData.value.specTagId,
    });
    // 更新数据
    console.log(res, "res");
    ElMessage.success("新增成功");
    setSpecData();
    specVisible.value = false;
    //emit("updateSpecTag");
  } catch (error) {
    console.error(error);
  }
};
// 编辑规格
const editProductSpec = async () => {
  console.log(specFormData.value, "编辑规格");
  try {
    await EquityMallAPI.editProductSpec({
      id: specFormData.value.id,
      name: specFormData.value.name,
      specTagId: specFormData.value.specTagId,
    });
    ElMessage.success("编辑成功");
    setSpecData();
    specVisible.value = false;
  } catch (error) {
    console.error(error);
  }
};
watch(
  async () => {
    if (props.specTypeOptions.length === 0) return;
    await setSpecData();
  },
  { immediate: true }
);
defineExpose({
  openDialog,
});
</script>

<style scoped></style>
